package com.eregg.learn.io.iochat;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class IOChatServer {
    public static void main(String args[]) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8000);

        Map<String, Socket> sockets = new HashMap<>();
        //1创建一个线程用来接收客户端请求
        new Thread(() -> {

            while (true) {
                try {
                    //1 阻塞方法获取一个新连接
                    Socket socket = serverSocket.accept();
                    //2 每一个新的连接都创建一个线程负责读取数据
                    new Thread(() -> {
                        try {
                            int len;
                            byte[] data = new byte[1024];
                            InputStream input = socket.getInputStream();
                            while ((len = input.read(data)) != -1) {
                                String message = new String(data, 0, len);
                                message.replace("\\r\\n", "");
                                String[] messages = message.trim().split(":");
                                if (messages[0].equals("login")) {
                                    sockets.put(messages[1], socket);
                                    socket.getOutputStream().write(("login success!!\r\n").getBytes());
                                } else {
                                    Socket targetUserSocket = sockets.get(messages[0]);
                                    if (targetUserSocket == null) {
                                        socket.getOutputStream().write(("User " + messages[0] + " does not exist\r\n").getBytes());
                                    } else {
                                        targetUserSocket.getOutputStream().write((messages[1] + "\r\n").getBytes());
                                    }
                                }
                            }
                        } catch (IOException e) {

                        }

                    }).start();
                } catch (IOException e) {

                }
            }

        }).start();
    }
}
